﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using BaseLinQ.DataContex;
namespace Module
{
    public class MenuLogic
    {
        string _conn = ConfigurationSettings.AppSettings["ConnectString"];
        RBACDataContext db = null;
        public List<tbl_Menu> lstMenu = null;
        public List<tbl_Menu> lstMenuTmp = null;


        /*-------------------------------------------------------------------------------------------------------------------------------*/
        /*-------------------------------------------------------------------------------------------------------------------------------*/
        /*-----------------------------------------------------------Generate Menu-------------------------------------------------------*/
        /*-------------------------------------------------------------------------------------------------------------------------------*/
        /*-------------------------------------------------------------------------------------------------------------------------------*/
        /// <summary>
        /// Lay danh sach menu
        /// </summary>
        /// <returns></returns>
        public List<tbl_Menu> GetListMenuByNguoiDungID(int _iNguoiDungID, long _iDonViID, long _iVaiTroID)
        {
            List<tbl_Menu> lstRes = new List<tbl_Menu>();
            db = new RBACDataContext(_conn);
            var objVTNDDV = from n in db.tbl_VaiTroNguoiDungDonVis
                           where n.fk_iNguoiDungID == _iNguoiDungID
                           && n.fk_iDonViID == _iDonViID
                           && n.fk_iVaiTroID == _iVaiTroID
                           && n.bKichHoat == true
                           select n;
            string check = "";
            foreach (tbl_VaiTroNguoiDungDonVi VTNDDV in objVTNDDV)
            {
                List<tbl_QuyenVaiTro> objQVT = (from i in db.tbl_QuyenVaiTros
                                                where i.fk_iVaiTroID == VTNDDV.fk_iVaiTroID
                                                select i).ToList<tbl_QuyenVaiTro>();
                if (objQVT != null && objQVT.Count > 0)
                {
                    foreach (tbl_QuyenVaiTro QVT in objQVT)
                    {
                        tbl_Quyen objQuyen = (from j in db.tbl_Quyens
                                              where j.pk_iQuyenID == QVT.fk_iQuyenID
                                              && j.bKichHoat == true
                                              select j).FirstOrDefault<tbl_Quyen>();
                        tbl_Menu objMenu = (from k in db.tbl_Menus
                                            where k.pk_iMenuID == objQuyen.fk_iMenuID
                                            && k.bKichHoat == true
                                            select k).FirstOrDefault<tbl_Menu>();
                        if (objMenu!= null && objMenu.pk_iMenuID.ToString() != check)
                        {
                            lstRes.Add(objMenu);
                            check = objMenu.pk_iMenuID.ToString();
                        }
                    }
                }
            }
            //return lstRes;
           return lstRes.OrderBy(x => x.fk_iMenuChaID).ToList<tbl_Menu>();
        }

        public List<tbl_Menu> GetListMenuByParentID(string type)
        {
            List<tbl_Menu> lstRes = new List<tbl_Menu>();
            db = new RBACDataContext(_conn);
            lstRes = (from n in db.tbl_Menus
                      where     n.bKichHoat == true
                        //n.fk_iMenuChaID == _iMenuID
                      select n).ToList<tbl_Menu>();
            db = null;
            return lstRes;
        }
        //Tim menu theo vai tro
        public List<tbl_Menu> GetListByVaiTro(string _iVaiTroID, string type)
        {
            List<tbl_Menu> lstRes = new List<tbl_Menu>();
            db = new RBACDataContext(_conn);
            var objQuyenVT = from m in db.tbl_QuyenVaiTros
                             orderby m.fk_iQuyenID ascending
                             where m.fk_iVaiTroID == int.Parse(_iVaiTroID)
                           select m;
            string ac = "";
            foreach (tbl_QuyenVaiTro QVT in objQuyenVT)
            {
                tbl_Quyen objQ = (from n in db.tbl_Quyens
                                  orderby n.fk_iMenuID ascending
                                  where n.pk_iQuyenID == QVT.fk_iQuyenID
                                  && n.bKichHoat == true
                                  select n).FirstOrDefault<tbl_Quyen>();
                
                tbl_Menu objMenu = (from i in db.tbl_Menus
                                    where i.pk_iMenuID == objQ.fk_iMenuID
                                    && i.bKichHoat == true
                                    && ac != objQ.fk_iMenuID.ToString()
                                    select i).FirstOrDefault<tbl_Menu>();
                if (objMenu != null)
                {
                    lstRes.Add(objMenu);
                    ac = objMenu.pk_iMenuID.ToString();
                }
            }
            db = null;
            return lstRes;
        }
        //
        //Lay ra menu root theo ID menu con
        public tbl_Menu GetMenuRoot(string _iMenuID)
        {
            db = new RBACDataContext(_conn);
            tbl_Menu Res = new tbl_Menu();
            tbl_Menu objMenucon = GetByID(long.Parse(_iMenuID));
            if (objMenucon.iCap == 1)
            {
                Res = objMenucon;
            }
            else
            {
                string parth = objMenucon.sPath;
                string[] p = parth.Split('/');
                Res = (from n in db.tbl_Menus
                       where n.bKichHoat == true
                       && n.iCap == 1
                       && n.sPath.Contains(p[1].ToString())
                       select n).FirstOrDefault<tbl_Menu>();
            }
            return Res;
        }
        //
        public List<tbl_Menu> GetMenucap(string _iMenuchaID)
        {
            db = new RBACDataContext(_conn);
            List<tbl_Menu> lstRes = (from menu in db.tbl_Menus
                                     where menu.fk_iMenuChaID == long.Parse(_iMenuchaID)
                                     && menu.bKichHoat == true
                                     select menu).ToList<tbl_Menu>();

            return lstRes;
        }
        //Lay menucon theo MenuRoot
        public List<tbl_Menu> GetMenuChild()
        {
            db=new RBACDataContext(_conn);
            List<tbl_Menu> lstRes = new List<tbl_Menu>();

            lstRes = (from menu in db.tbl_Menus
                     where menu.bKichHoat == true
                     //&& menu.sPath.Contains(_iMenuRootID)
                     select menu).ToList<tbl_Menu>();

            return lstRes;
        }
        //Lọc menu theo người dùng, vai trò, đơn vị
        public List<tbl_Menu> FilterValidMenu(string _iNguoiDungID, string _iVaitroID, string _iDonViID, List<tbl_Menu> lstMenuTong)
        {
            List<tbl_Menu> lstRes = new List<tbl_Menu>();
            List<tbl_Menu> lstValidMenu = GetListMenuByNguoiDungID(int.Parse(_iNguoiDungID), long.Parse(_iDonViID), long.Parse(_iVaitroID));
            if (lstValidMenu != null && lstValidMenu.Count > 0)
            {
                lstRes = (from m in lstMenuTong
                          orderby m.fk_iMenuChaID ascending
                          where (from valid in lstValidMenu select valid.pk_iMenuID).Contains(m.pk_iMenuID)
                          select m).ToList<tbl_Menu>();
            }
            return lstRes;
        }

        //Lay menu cha theo ID menu con
        public tbl_Menu GetMenuCha(string _iMenuconID)
        {
            db = new RBACDataContext(_conn);
            tbl_Menu objMenucon = GetByID(long.Parse(_iMenuconID));
            tbl_Menu objRes = (from n in db.tbl_Menus
                               where n.bKichHoat == true
                               && n.pk_iMenuID == objMenucon.fk_iMenuChaID
                               select n).FirstOrDefault<tbl_Menu>();

            return objRes;
        }
        //gen menu cha theo ID menu con
        public string GenMenuCha(string _iMenuconID)
        {
            string _html = "";
            db = new RBACDataContext(_conn);
            tbl_Menu objMenuCon = GetByID(long.Parse(_iMenuconID));
            string _url = "Admin/" + objMenuCon.pk_iMenuID + "/" + objMenuCon.sTenControl + "/" + "Default.aspx";
            if (objMenuCon.sTenControl == "" || objMenuCon.sTenControl == null)
            {
                _url = "#";
            }
            if (objMenuCon.iCap > 1)
            {
                tbl_Menu objMenucha = GetMenuCha(_iMenuconID);
                _html += GenMenuCha(objMenucha.pk_iMenuID.ToString());
                
                _html += "<ul><li><a href='" + _url + "'>" + objMenuCon.sTenMenu + "</a>";
            }
            if (objMenuCon.iCap == 1)
            {
                _html += "<li><a href='" + _url + "'>" + objMenuCon.sTenMenu + "</a>";
            }
            return _html;
        }
        public string GenMenuChaLeft(string _iMenuconID)
        {
            string _html = "";
            db = new RBACDataContext(_conn);
            tbl_Menu objMenuCon = GetByID(long.Parse(_iMenuconID));
            string _url = "Admin/" + objMenuCon.pk_iMenuID + "/" + objMenuCon.sTenControl + "/" + "Default.aspx";
            if (objMenuCon.sTenControl == "" || objMenuCon.sTenControl == null)
            {
                _url = "#";
            }
            if (objMenuCon.iCap > 1)
            {
                tbl_Menu objMenucha = GetMenuCha(_iMenuconID);
                _html += GenMenuChaLeft(objMenucha.pk_iMenuID.ToString());

                _html += "<ul><li><a href='" + _url + "'>" + objMenuCon.sTenMenu + "</a>";
            }
            if (objMenuCon.iCap == 1)
            {
                _html += "<div class='submenu'><ul><li><a href='" + _url + "'>" + objMenuCon.sTenMenu + "</a>";
            }
            return _html;
        }
        public string GenMenuLeftCha(string _iMenuconID)
        {
            string _html = "";
            db = new RBACDataContext(_conn);
            tbl_Menu objMenuCon = GetByID(long.Parse(_iMenuconID));
            string _url = "Admin/" + objMenuCon.pk_iMenuID + "/" + objMenuCon.sTenControl + "/" + "Default.aspx";
            if (objMenuCon.sTenControl == "" || objMenuCon.sTenControl == null)
            {
                _url = "#";
            }
            if (objMenuCon.iCap > 1)
            {
                tbl_Menu objMenucha = GetMenuCha(_iMenuconID);
                _html += GenMenuCha(objMenucha.pk_iMenuID.ToString());

                _html += "<ul><li><a href='" + _url + "'>" + objMenuCon.sTenMenu + "</a>";
            }
            if (objMenuCon.iCap == 1)
            {
                _html += "<a class='menuitem submenuheader' href=''>" + objMenuCon.sTenMenu + "</a><div class='submenu'>";
            }
            return _html;
        }
        //



        

        /*-------------------------------------------------------------------------------------------------------------------------------*/
        /*------------------------------------------------------------END----------------------------------------------------------------*/
        /*-------------------------------------------------------------------------------------------------------------------------------*/
        public List<tbl_Menu> GetList()
        {
            List<tbl_Menu> lstRes = null;
            db = new RBACDataContext(_conn);
            try
            {
                lstRes = (from m in db.tbl_Menus
                                          where m.bKichHoat == true
                                          select m).ToList<tbl_Menu>();
            }
            catch (Exception ex)
            {
            }
            db = null;
            return lstRes;
        }

        /// <summary>
        /// Lay danh sach menu phan cap
        /// </summary>
        /// <returns></returns>
        public List<tbl_Menu> GetTreeMenu()
        {
            db = new RBACDataContext(_conn);
            List<tbl_Menu> lstRes = null;
            string strPrefix = "";
            try
            {
                lstRes = (from m in db.tbl_Menus
                          orderby m.iSoThuTu ascending
                          where m.bKichHoat == true
                          && m.iCap == 1
                          select m).ToList<tbl_Menu>();
                if (lstRes != null && lstRes.Count > 0)
                {
                    lstMenu = new List<tbl_Menu>();
                    foreach (tbl_Menu objMenu in lstRes)
                    {
                        strPrefix = objMenu.iSoThuTu + "";
                        objMenu.sTenMenu = strPrefix + ". " + objMenu.sTenMenu;
                        lstMenu.Add(objMenu);
                        GetTreeMenuChild(objMenu.pk_iMenuID, strPrefix);
                    }
                }
            }
            catch (Exception ex)
            {
               
            }
            db = null;
            return lstMenu;
        }

        /// <summary>
        /// Lấy danh sách menu con
        /// </summary>
        /// <param name="_lngParentMenuID"></param>
        /// <returns></returns>
        public void GetTreeMenuChild(long _lngParentMenuID, string _strPrefix)
        {
            db = new RBACDataContext(_conn);
            string strPrefix = "";
            try
            {
                lstMenuTmp = (from m in db.tbl_Menus
                              orderby m.iSoThuTu ascending
                          where m.bKichHoat == true
                          && m.fk_iMenuChaID == _lngParentMenuID
                          select m).ToList<tbl_Menu>();
                if (lstMenuTmp != null && lstMenuTmp.Count > 0)
                {
                    foreach (tbl_Menu objMenu in lstMenuTmp)
                    {
                        strPrefix = "";
                        strPrefix += _strPrefix + "." + objMenu.iSoThuTu + "";
                        objMenu.sTenMenu = strPrefix + ". " + objMenu.sTenMenu;
                        lstMenu.Add(objMenu);
                        GetTreeMenuChild(objMenu.pk_iMenuID, strPrefix);
                    }
                }
            }
            catch (Exception ex)
            {
                
            }
            db = null;
        }

        /// <summary>
        /// Lay danh sach menu phan cap cho combobox
        /// </summary>
        /// <returns></returns>
        public List<tbl_Menu> GetTreeMenuForCbo(long _lngMenuID)
        {
            tbl_Menu objMenuCurrent = GetByID(_lngMenuID);
            int iLevel = objMenuCurrent != null ? (int)objMenuCurrent.iCap : 100; // MAX level = 100
            db = new RBACDataContext(_conn);
            List<tbl_Menu> lstRes = null;
            string strPrefix = "";
            try
            {
                lstRes = (from m in db.tbl_Menus
                          orderby m.iSoThuTu ascending
                          where m.bKichHoat == true
                          && (m.iCap == 1 || m.fk_iMenuChaID == null)
                          select m).ToList<tbl_Menu>();
                if (lstRes != null && lstRes.Count > 0)
                {
                    lstMenu = new List<tbl_Menu>();
                    foreach (tbl_Menu objMenu in lstRes)
                    {
                        strPrefix = objMenu.iSoThuTu + "";
                        objMenu.sGhiChu = "<b class='red'>" + strPrefix + ".</b>&nbsp;" + objMenu.sTenMenu;
                        lstMenu.Add(objMenu);
                        if (objMenu.iCap < iLevel)
                        {
                            GetTreeMenuChildForCbo(objMenu.pk_iMenuID, strPrefix, iLevel);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                 
            }
            db = null;
            return lstMenu;
        }

        /// <summary>
        /// Lấy danh sách menu con cho combobox
        /// </summary>
        /// <param name="_lngParentMenuID"></param>
        /// <returns></returns>
        public void GetTreeMenuChildForCbo(long _lngParentMenuID, string _strPrefix, int _intLevel)
        {
            db = new RBACDataContext(_conn);
            string strPrefix = "";
            try
            {
                lstMenuTmp = (from m in db.tbl_Menus
                              orderby m.iSoThuTu ascending
                              where m.bKichHoat == true
                              && m.fk_iMenuChaID == _lngParentMenuID
                              && m.iCap < _intLevel
                              select m).ToList<tbl_Menu>();
                if (lstMenuTmp != null && lstMenuTmp.Count > 0)
                {
                    foreach (tbl_Menu objMenu in lstMenuTmp)
                    {
                        strPrefix = "";
                        strPrefix += "&nbsp;&nbsp;" + _strPrefix + "." + objMenu.iSoThuTu + "";
                        objMenu.sGhiChu = "<b class='red'>" + strPrefix + ".</b>&nbsp;" + objMenu.sTenMenu;
                        lstMenu.Add(objMenu);
                        if (objMenu.iCap < _intLevel)
                        {
                            GetTreeMenuChildForCbo(objMenu.pk_iMenuID, strPrefix, _intLevel);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                
            }
            db = null;
        }

        /// <summary>
        /// Lấy menu theo ID
        /// </summary>
        /// <param name="_lngMenuID"></param>
        /// <returns></returns>
        public tbl_Menu GetByID(long _lngMenuID)
        {
           tbl_Menu objRes = null;
            db = new RBACDataContext(_conn);
            try
            {
                objRes = (from m in db.tbl_Menus
                          where m.bKichHoat == true
                          && m.pk_iMenuID == _lngMenuID
                          select m).FirstOrDefault<tbl_Menu>();
            }
            catch (Exception ex)
            {
                
            }
            return objRes;
        }

        /// <summary>
        /// Them moi menu
        /// </summary>
        /// <param name="_objMenu"></param>
        /// <returns></returns>
        public bool Insert(tbl_Menu _objMenu)
        {
            bool blnFalse = false;
            db = new RBACDataContext(_conn);
            try
            {
                if(_objMenu.fk_iMenuChaID != null && _objMenu.fk_iMenuChaID != 0)
                {
                    tbl_Menu objMenuParent = GetByID((long)_objMenu.fk_iMenuChaID);
                    if (objMenuParent != null && objMenuParent.pk_iMenuID > 0)
                    {
                        _objMenu.iCap = objMenuParent.iCap + 1;
                        objMenuParent = null;
                    }
                }
                else
                {
                    _objMenu.iCap = 1;
                }
                if (_objMenu.fk_iMenuChaID != null)
                {
                    tbl_Menu checkr = (from m in db.tbl_Menus
                                       where m.iSoThuTu == _objMenu.iSoThuTu
                                       && m.fk_iMenuChaID == _objMenu.fk_iMenuChaID
                                       && m.bKichHoat == true
                                       select m).FirstOrDefault<tbl_Menu>();
                    if (checkr != null)
                    {
                        blnFalse = false;
                    }
                    else
                    {
                        _objMenu.dNgayTao = DateTime.Now;
                        _objMenu.dNgayCapNhat = DateTime.Now;
                        db.tbl_Menus.InsertOnSubmit(_objMenu);
                        db.SubmitChanges();
                        blnFalse = true;
                    }
                }
                if (_objMenu.fk_iMenuChaID == null)
                {
                    tbl_Menu checkr = (from m in db.tbl_Menus
                                       where m.iSoThuTu == _objMenu.iSoThuTu
                                       && m.fk_iMenuChaID == null
                                       && m.bKichHoat == true
                                       select m).FirstOrDefault<tbl_Menu>();
                    if (checkr != null)
                    {
                        blnFalse = false;
                    }
                    else
                    {
                        _objMenu.dNgayTao = DateTime.Now;
                        _objMenu.dNgayCapNhat = DateTime.Now;
                        db.tbl_Menus.InsertOnSubmit(_objMenu);
                        db.SubmitChanges();
                        blnFalse = true;
                    }
                }
                
            }
            catch (Exception ex)
            {
                
            }
            db = null;
            return blnFalse;
        }

        /// <summary>
        /// Cap nhat thong tin menu
        /// </summary>
        /// <param name="_objMenuNew"></param>
        /// <returns></returns>
        public bool Update(tbl_Menu _objMenuNew)
        {
            bool blnRes = false;
            db = new RBACDataContext(_conn);
            try
            {
                tbl_Menu objMenuOld = (from m in db.tbl_Menus
                                       where m.pk_iMenuID == _objMenuNew.pk_iMenuID
                                       select m).FirstOrDefault<tbl_Menu>();
                if (objMenuOld != null && objMenuOld.pk_iMenuID > 0)
                {
                    objMenuOld.sTenMenu = _objMenuNew.sTenMenu;
                    objMenuOld.sTenControl = _objMenuNew.sTenControl;
                    objMenuOld.sGhiChu = _objMenuNew.sGhiChu;
                    objMenuOld.sPath = _objMenuNew.sPath;
                    if (objMenuOld.fk_iMenuChaID != _objMenuNew.fk_iMenuChaID)
                    {
                        objMenuOld.fk_iMenuChaID = _objMenuNew.fk_iMenuChaID;
                        try
                        {
                            tbl_Menu objMenuParent = (from m in db.tbl_Menus
                                                      where m.bKichHoat == true
                                                      && m.pk_iMenuID == _objMenuNew.fk_iMenuChaID
                                                      select m).FirstOrDefault<tbl_Menu>();
                            if (objMenuParent != null && objMenuParent.pk_iMenuID > 0)
                            {
                                objMenuOld.iCap = objMenuParent.iCap + 1;
                            }
                            objMenuParent = null;
                        }
                        catch (Exception ex)
                        {
                            
                        }
                    }
                    objMenuOld.iSoThuTu = _objMenuNew.iSoThuTu;
                    objMenuOld.sKieuMenu = _objMenuNew.sKieuMenu;
                    objMenuOld.sTenThuMuc = _objMenuNew.sTenThuMuc;
                    objMenuOld.fk_iNguoiCapNhatID = _objMenuNew.fk_iNguoiCapNhatID;
                    objMenuOld.dNgayCapNhat = DateTime.Now;
                    db.SubmitChanges();
                    blnRes = true;
                }
            }
            catch (Exception ex)
            {
                
            }
            db = null;
            return blnRes;
        }

        /// <summary>
        /// Xoa menu
        /// </summary>
        /// <param name="_pk_iMenuID"></param>
        /// <returns></returns>

        public bool CheckMenuCon(long _pk_iMenuID)
        {
            bool blnRes = false;
            db = new RBACDataContext(_conn);
            try
            {
                tbl_Menu objMenuCon = (from m in db.tbl_Menus
                                       where m.fk_iMenuChaID == _pk_iMenuID
                                       && m.bKichHoat == true
                                       select m).FirstOrDefault<tbl_Menu>();
                if (objMenuCon != null && objMenuCon.pk_iMenuID > 0)
                {
                    blnRes = true;
                }
            }
            catch (Exception ex)
            {
                
            }
            return blnRes;
        }
        public bool Delete(long _pk_iMenuID)
        {
            bool blnRes = false;
            db = new RBACDataContext(_conn);
            try
            {
                tbl_Menu objMenuOld = (from m in db.tbl_Menus
                                       where m.pk_iMenuID == _pk_iMenuID
                                       select m).FirstOrDefault<tbl_Menu>();
                if (objMenuOld != null && objMenuOld.pk_iMenuID > 0)
                {
                    objMenuOld.bKichHoat = false;
                    db.SubmitChanges();
                    blnRes = true;
                }
            }
            catch (Exception ex)
            {
                
            }
            db = null;
            return blnRes;
        }
    }
    
}
